package com.xgst.lovevideocall.viewmodel

import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.blankj.utilcode.util.ToastUtils
import com.gym.baselib.base.BaseViewModel
import com.hjq.http.EasyHttp
import com.hjq.http.listener.OnHttpListener
import com.xgst.lovevideocall.bean.RongLoginBean
import com.xgst.runningmanager.bean.DataR
import com.xgst.runningmanager.bean.LoopMsgBean
import com.xgst.runningmanager.constant.RongKey
import com.xgst.runningmanager.http.api.LoopMsgAPI
import com.xgst.runningmanager.http.api.RongGroupAPI
import com.xgst.runningmanager.http.api.RongLoginAPI
import io.rong.imlib.RongIMClient

class RongViewModel : BaseViewModel() {
    private var phone = ""
    fun loginAndConnect(phone:String, onConnect:()->Unit, onError:(String)->Unit = {}){
        this.phone = phone
        rongLogin(phone,{
            LogUtils.i("登录成功,开始连接")
            connect(it,onConnnectSuccess = onConnect,onError = onError)
        },{
            onError(it)
        })
    }

    private fun rongLogin(userId:String,onResult:(String)->Unit,onError:(String)->Unit = {}){
        EasyHttp.post(this)
            .api(RongLoginAPI().setUserId(userId))
            .request(object : OnHttpListener<RongLoginBean> {
                override fun onHttpSuccess(bean: RongLoginBean) {
                    SPStaticUtils.put(RongKey.RONG_TOKEN,bean.token)
                    SPStaticUtils.put(RongKey.RONG_USER_ID,bean.userId)
                    onResult(bean.token)
                }

                override fun onHttpFail(error: Throwable) {
                    ToastUtils.showShort("注册失败:${error.message}")
                    LogUtils.file("融云注册失败${error.message}")
                    onError("融云注册失败${error.message}")
                }
            })
    }

    fun connect(token: String,onConnnectSuccess:()->Unit = {},onError:(String)->Unit = {}) {
        val currentConnectionStatus = RongIMClient.getInstance().currentConnectionStatus
        if (currentConnectionStatus == RongIMClient.ConnectionStatusListener.ConnectionStatus.CONNECTED) {
            onConnnectSuccess()
            return
        }

        RongIMClient.connect(token,object : RongIMClient.ConnectCallback(){
            override fun onSuccess(userId: String?) {
                LogUtils.i("连接成功: $userId")
                onConnnectSuccess()
            }

            override fun onError(errorCode: RongIMClient.ConnectionErrorCode?) {
                LogUtils.i("连接融云失败 ${errorCode?.name} - ${errorCode?.value}")
                onError("连接失败:${errorCode}")
            }

            override fun onDatabaseOpened(p0: RongIMClient.DatabaseOpenStatus?) {
            }
        })
    }

    fun loopMsg(onResult: (DataR) -> Unit){
        EasyHttp.post(this)
            .api(LoopMsgAPI())
            .request(object : OnHttpListener<LoopMsgBean> {
                override fun onHttpSuccess(bean: LoopMsgBean) {
                    if(bean.result.size > 0){
                        onResult(bean.result[0])
                    }
                }

                override fun onHttpFail(error: Throwable) {
                    LogUtils.file("轮询：${error.message}")
                }
            })
    }

    fun createGroup(){
        EasyHttp.post(this)
            .api(RongGroupAPI().setUserId("xgst111"))
            .request(object : OnHttpListener<RongLoginBean> {
                override fun onHttpSuccess(bean: RongLoginBean) {
                    LogUtils.i("创建群组成功")
                }

                override fun onHttpFail(error: Throwable) {
                    LogUtils.file("群组${error.message}")
                }
            })
    }

}